//
//  HDCFMyBankCardVc.m
//  HaoDeCaiFu
//
//  Created by 郑开宏 on 2017/11/9.
//  Copyright © 2017年 郑开宏. All rights reserved.
//

#import "HDCFMyBankCardVc.h"
#import "MyBankCardCell.h"
#import "AddBankCardTableViewController.h"
#import "HDCFOpenAccountCell.h"
#import "SVProgressHUD.h"
#import "WalletView.h"
#define KBankCardInfo @"/public/transaction/get-investor-payment-method"

@interface HDCFMyBankCardVc ()<UIAlertViewDelegate>

@property (nonatomic, strong) NSDictionary *deleteDic;
@property (nonatomic, strong) WalletView *wallet;

@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSArray *bankArray;

@property(nonatomic,copy)NSString* yue;

@end

@implementation HDCFMyBankCardVc


-(void)viewWillAppear:(BOOL)animated
{
     [self getBankCardInfo];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden=NO;
    [self.navigationItem setTitle:@"我的银行卡"];
    [self getMyWalltInfo];
    
//    UIBarButtonItem*rightItem=[[UIBarButtonItem alloc]initWithTitle:@"添加" style:UIBarButtonItemStylePlain target:self action:@selector(addBtnClick)];
//    self.navigationItem.rightBarButtonItem=rightItem;
    
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
//    if (!kBankList) {
//        [self getAllBanInfo];
//    }
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSMutableArray *array = [NSMutableArray arrayWithArray:[user objectForKey:@"bankList"]];
    if (!array||array.count==0) {
        [self initData];
    }
    
}


- (void)getMyWalltInfo{
    NSMutableDictionary *paramets = [NSMutableDictionary dictionary];
    
    paramets[@"accountNumber"] = kAcount;
    NSString *jsonStr = [self dictionaryToJson:paramets];
    NSDictionary *paramet = @{KparametOne:jsonStr,
                              KparametTwo:@"/public/wallet/get-cash-wallet-holdings"};
    LSWeakSelf;
    [HttpRequest sendGetRequestWithURL:nil WithParamets:paramet success:^(id result) {
        NSString *code = result[@"code"];
       
        if ([code isEqualToString:@"0000"]) {
            NSDictionary *dataDic = result[@"data"];
            NSArray *dataArray = dataDic[@"data"];
            for (NSDictionary*dic in dataArray) {
               
                self.yue=[NSString stringWithFormat:@"%.2f元",  [[dic objectForKey:@"availableValue"] floatValue]];
                NSIndexSet *set=[NSIndexSet indexSetWithIndex:0];
                [weakSelf.tableView reloadSections:set withRowAnimation:UITableViewRowAnimationNone];
               
            }
        }else{
            [SVProgressHUD showInfoWithStatus:result[@"message"]];
            [SVProgressHUD dismissWithDelay:1.0];
        }
        
    } failure:^(NSError *errer) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
        [SVProgressHUD dismissWithDelay:1.0];
    }];
    
}




- (void)initData{
    [SVProgressHUD show];
    NSDictionary *paramet = @{
                              KparametTwo:@"/public/investor/find-bank"
                              };
    [HttpRequest sendGetRequestWithURL:nil WithParamets:paramet success:^(id result) {
//        [SVProgressHUD showSuccessWithStatus:@"获取成功"];
//        [SVProgressHUD dismissWithDelay:1.0];
       
        NSString *code = result[@"code"];
        
        if ([code isEqualToString:@"0000"]) {
            
            NSDictionary *dict = result[@"data"];
            self.bankArray = [NSArray arrayWithArray:dict[@"data"]];
            
            NSMutableArray *array = [NSMutableArray arrayWithArray:dict[@"data"]];
            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
            [user setObject:array forKey:@"bankList"];
            [user synchronize];
            
            [self.tableView reloadData];
            
        }else{
            [SVProgressHUD showInfoWithStatus:result[@"message"]];
            [SVProgressHUD dismissWithDelay:1.0];
        }
        
        
    } failure:^(NSError *errer) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
        [SVProgressHUD dismissWithDelay:1.0];
    }];
}
//-(void)addBankCardView
//{
//    UIView*addView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, 60)];
//    addView.backgroundColor=[UIColor whiteColor];
//    UIButton*addBtn=[UIButton buttonWithType:UIButtonTypeCustom];
//    addBtn.frame=CGRectMake(10, 0, screenWidth-50, <#CGFloat height#>)
//    
//}



- (void)getAllBanInfo{
    [SVProgressHUD show];
    NSDictionary *paramet = @{
                              KparametTwo:@"/public/transaction/get-investor-payment-method"
                              };
    [HttpRequest sendGetRequestWithURL:nil WithParamets:paramet success:^(id result) {
        
        NSString *code = result[@"code"];
        
        if ([code isEqualToString:@"0000"]) {
            
            [SVProgressHUD dismiss];
            NSDictionary *dict = result[@"data"];
            self.bankArray = [NSArray arrayWithArray:dict[@"data"]];
            
            NSMutableArray *array = [NSMutableArray arrayWithArray:dict[@"data"]];
            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
            [user setObject:array forKey:@"bankList"];
            [user synchronize];
            [self.tableView reloadData];
            
            
        }else{
            [SVProgressHUD showInfoWithStatus:result[@"message"]];
            [SVProgressHUD dismissWithDelay:1.0];
        }
        
//        [SVProgressHUD showSuccessWithStatus:@"获取成功"];
//        [SVProgressHUD dismissWithDelay:1.0];
     
        
    } failure:^(NSError *errer) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
        [SVProgressHUD dismissWithDelay:1.0];
    }];
    
}
    
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

- (NSString *)dictionaryToJson:(NSDictionary *)dic{
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
- (void)getBankCardInfo{
    NSMutableDictionary *paramets = [NSMutableDictionary dictionary];
    
    paramets[@"accountNumber"] = kAcount;
    NSString *jsonStr = [self dictionaryToJson:paramets];
    NSDictionary *paramet = @{KparametOne:jsonStr,
                              KparametTwo:KBankCardInfo};
    
    [HttpRequest sendGetRequestWithURL:nil WithParamets:paramet success:^(id result) {
        NSString *code = result[@"code"];
        if ([code isEqualToString:@"0000"]) {
            NSDictionary *dict = result[@"data"];
            NSDictionary *dictTwo = dict[@"investorBankDetails"];
            self.dataArray = dictTwo[@"data"];
            [self.tableView reloadData];
        }else{
            [SVProgressHUD showInfoWithStatus:result[@"message"]];
            [SVProgressHUD dismissWithDelay:1.0];
        }
        
    } failure:^(NSError *errer) {
        [SVProgressHUD showErrorWithStatus:@"获取银行卡信息失败"];
        [SVProgressHUD dismissWithDelay:1.0];
    }];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if (section==1) {
        return self.dataArray.count;
    }
    else
    {
        
       if (section==0) {
           if (self.isXianshiWallet==YES) {
                return 1;
            }
            else
            {
                return 0;
            }
        }
        return 1;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (indexPath.section==0) {
        return 120 ;
    }
    else if (indexPath.section==1) {
        return 142;
    }
    else
    {
        return 60;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellID = @"cellid";
    if (indexPath.section==1) {
        MyBankCardCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (!cell) {
            cell = [MyBankCardCell MyBankCardCell];
        }
        
        NSDictionary *bankInfo = self.dataArray[indexPath.row];
        NSString *imageName = [NSString stringWithFormat:@"icon_%@", bankInfo[@"bankCode"]];
        cell.iconImageView.image = [UIImage imageNamed:imageName];
        
        NSString *cardNo = bankInfo[@"bankNumber"];
        NSString *cardNoF = [cardNo substringFromIndex:cardNo.length - 4];
        cell.bankNO.text = [NSString stringWithFormat:@"**** **** **** %@", cardNoF];
        
        NSString *bgImageName = [NSString stringWithFormat:@"bg_%@", bankInfo[@"bankCode"]];
        cell.backImgView.image = [UIImage imageNamed:bgImageName];
        
        //    if (kBankList) {
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSMutableArray *array = [NSMutableArray arrayWithArray:[user objectForKey:@"bankList"]];
        for (int i = 0; i < array.count; i++) {
            NSDictionary *dictBank = array[i];
            if ([dictBank[@"bankCode"] isEqualToString:bankInfo[@"bankCode"]]) {
                cell.bankName.text = dictBank[@"bankName"];
                NSLog(@"%@", dictBank[@"bankName"]);
                //                [2]    (null)    @"singleTransactionLimit" : (double)500000
                //                [3]    (null)    @"dailyTradingLimit" : (long)2000000
                NSNumber *one = dictBank[@"singleTransactionLimit"];
                NSNumber *day = dictBank[@"dailyTradingLimit"];
                cell.limitMoney.text = [NSString stringWithFormat:@"单笔:%.2f万元, 单日:%.2f万元", one.doubleValue / 10000, day.doubleValue / 10000];
                break;
            }
            //        }
        }
        
        if (self.isHiddenDeleteBtn == YES) {
            cell.closeBtn.hidden = YES;
        }
        
        if ([bankInfo[@"preferred"] isEqualToString:@"Y"]) {
            cell.closeBtn.hidden=YES;
        }
        
        
        cell.closeBtn.tag=indexPath.row;
        [cell.closeBtn addTarget:self action:@selector(closeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    else if (indexPath.section==0)
    {
        UITableViewCell*cell=[[UITableViewCell alloc]init];
      
            self.wallet=[WalletView fixTrowSetView];
            _wallet.frame=CGRectMake(16, 15, screenWidth-20, 100);
            _wallet.backgroundColor=[UIColor whiteColor];
            _wallet.clipsToBounds=YES;
            _wallet.layer.cornerRadius=5;
            _wallet.layer.borderColor=ZKcolor(240, 240, 240).CGColor;
            _wallet.layer.borderWidth=0.5;
            _wallet.lastDayShouyiLable.hidden=YES;
            _wallet.shouyiLable.hidden=YES;
        _wallet.xianzhiLable.text=self.yue;
            _wallet.backgroundColor=[UIColor whiteColor];
            cell.contentView.frame = CGRectMake(0, 0, screenWidth+20, 120);
      
       
        [cell.contentView addSubview:_wallet];
      
        return cell;
    }
    else
    {
        HDCFOpenAccountCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (!cell) {
            cell = [HDCFOpenAccountCell HDCFOpenAccountCell];
        }
        UIView*lineView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, 0.5)];
        lineView.backgroundColor=ZKcolor(240, 240, 240);
        [cell.contentView addSubview:lineView];
         cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.imgView.image=[UIImage imageNamed:@"icon_tianjia"];
         cell.textTf.text = @"添加银行卡";
        cell.textTf.enabled=NO;
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        [cell.sendCodeBtn removeFromSuperview];
        UIView*lineView1=[[UIView alloc]initWithFrame:CGRectMake(0, 59.5, screenWidth, 0.5)];
        lineView1.backgroundColor=ZKcolor(240, 240, 240);
        [cell.contentView addSubview:lineView1];
       
        return cell;
    }
}


-(void)closeBtnClick:(UIButton*)btn
{
     self.deleteDic= self.dataArray[btn.tag];
    UIAlertView*alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"您确认要删除该张银行卡吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
    [alert show];
    
    
    
    
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex==1) {
        [SVProgressHUD show];
        NSMutableDictionary *dictOne = [NSMutableDictionary dictionary];
        dictOne[@"investorPayId"] = self.deleteDic[@"investorPayId"];
        dictOne[@"accountNumber"] = kAcount;
        
        NSString *jsonString = [self dictionaryToJson:dictOne];
        NSDictionary *paramet = @{
                                  KparametTwo:@"/public/investor/unbind-bank",
                                  KparametOne:jsonString
                                  };
         LSWeakSelf;
        [HttpRequest sendPostRequestWithURL:nil WithParamets:paramet WithJsonString:nil success:^(id result) {
            if ([result[@"code"] isEqualToString:@"0000"]) {
                
               
                [weakSelf.dataArray removeObject:weakSelf.deleteDic];
                [weakSelf.tableView reloadData];
                [SVProgressHUD  dismissWithDelay:1.0];
                
                
            }else{
                [SVProgressHUD showInfoWithStatus:result[@"message"]];
                [SVProgressHUD  dismissWithDelay:1.0];
            }
            
        } failure:^(NSError *errer) {
            [SVProgressHUD showErrorWithStatus:@"网络错误"];
            [SVProgressHUD  dismissWithDelay:1.0];
        }];
    }
    

    
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section==0) {
        self.block(self.yue, @"",@"",NO);
        [self.navigationController popViewControllerAnimated:YES];
    }
    
    
    if (indexPath.section == 1) {
        if ([_delegate respondsToSelector:@selector(HDCFMyBankCardVcReturnSelectIndex:bankCardArray:)]) {
            [_delegate HDCFMyBankCardVcReturnSelectIndex:indexPath.row bankCardArray:self.dataArray];
            
            [self.navigationController popViewControllerAnimated:YES];
            return;
        }
        
        
        if (self.isNeedBlock==YES) {
            NSDictionary *bankInfo = self.dataArray[indexPath.row];
            NSString *cardNo = bankInfo[@"bankNumber"];
            NSString *cardNoF = [cardNo substringFromIndex:cardNo.length - 4];
            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
            NSMutableArray *array = [NSMutableArray arrayWithArray:[user objectForKey:@"bankList"]];
            for (int i = 0; i < array.count; i++) {
                NSDictionary *dictBank = array[i];
                if ([dictBank[@"bankCode"] isEqualToString:bankInfo[@"bankCode"]]) {
                    
                    self.block(dictBank[@"bankName"], cardNoF,bankInfo[@"investorPayId"],YES);
                    [self.navigationController popViewControllerAnimated:YES];
                    
                    break;
                }
                //        }
            }
        }
       
        
    }
    if (indexPath.section==2) {
        AddBankCardTableViewController*vc=[[AddBankCardTableViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}
/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
